<template>
  <view class="container">
    <!-- 维修方式 -->
    <view class="repair-mode">
      <text>维修方式:</text>
      <radio-group @change="(e) => formData.type = e.detail.value">
        <label> <radio value="0" :checked="formData.type === '0'">到店维修</radio> </label>
        <label style="margin-left: 50rpx;"> <radio value="1" :checked="formData.type === '1'">上门取车</radio> </label>
      </radio-group>
    </view>

    <!-- 客户信息 -->
    <view class="customer-info">
      <text class="section-title">客户信息</text>
      <view class="form-item">
        <text>车主姓名:</text>
        <input type="text" placeholder="请输入车主姓名" v-model="formData.name">
      </view>
      <view class="form-item">
        <text>联系方式:</text>
        <input type="text" placeholder="请输入联系方式" v-model="formData.phone">
      </view>
      <view class="form-item">
        <text style="margin-right: 30px;">预约时间:</text>
        <uni-datetime-picker type="datetime" v-model="formData.reservationTime" @change="changeLog" />
      </view>
	  <view class="form-item" v-show="formData.type==='1'">
	    <text>取车位置:</text>
	    <input type="text" placeholder="请输入取车位置" v-model="formData.location">
	  </view>
    </view>
    <!-- 车辆信息 -->
    <view class="vehicle-info">
      <text class="section-title">车辆信息</text>
      <view class="form-item">
        <text>车辆类型:</text>
        <uni-data-select
          v-model="formData.carTypeId"
          :localdata="vehicleOptions"
          @change="onVehicleTypeChange"
          :clear="false"
          placeholder="请选择车辆类型"
        ></uni-data-select>
      </view>
      <view class="form-item">
        <text>车牌号:</text>
        <input type="text" placeholder="请输入车牌号" v-model="formData.carNum">
      </view>
    </view>
	 <!-- 照片 -->
    <view class="photo-info">
      <text class="section-title">照片</text>
      <view class="form-item">
        <text>整车照片:</text>
        <uni-file-picker
        	v-model="vehiclePhotos"  
        	file-mediatype="image"
        	mode="grid"
        	file-extname="png,jpg"
        	:limit="1"
        	@select="select"
        />
      </view>
	  <view class="form-item">
	    <text>维修部位:</text>
	    <uni-file-picker
	    	v-model="repairPhotos"  
	    	file-mediatype="image"
	    	mode="grid"
	    	file-extname="png,jpg"
	    	:limit="3"
	    	@select="select2"
	    />
	  </view>
     
    </view>
    <!-- 提交按钮 -->
    <button class="submit-button" type="primary" @click="submitForm">提交</button>

   <!--  提交按钮
     <button class="submit-button" type="primary" @click="submitForm1">提交2</button> -->
  
	
	<!-- <canvas id="qrcode" canvas-id="qrcode" style="width: 100px;height: 100px;"></canvas> -->
	
  </view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue';
import baseUrl from '../../utils/urlConfig.js'
import { formatDateTime } from '../../utils/dateUtil.js';
//  预约时间
function changeLog(e) {
  const selectedTime = new Date(e).getTime();
  const currentTime = new Date().getTime();
  if (selectedTime < currentTime) {
    uni.showToast({
      title: '预约时间不能早于当前时间',
      icon: 'none'
    });
    formData.value.reservationTime = ''; // 清空选择的时间
    return;
  }
  formData.value.reservationTime = e;
}
onLoad((options)=>{
// 商家id
	 formData.value.mid=options.id
  getUserInfo()
})
// 获取用户信息
function getUserInfo() {
  const userInfo = uni.getStorageSync('user');
  formData.value.uid = userInfo.id;
}
// 获取商家id




const formData = ref({
	id:'', 
	verificationCode:'', //核销码
	verificationImg:'' ,// 核销码图片
	mid:'',
	uid:'',
	type:'0',  //维修方式
	name:'', //车主名称
	phone:'', //车主电话
	reservationTime:'', //预约时间
	submitTime:'',  //交车时间
	location:'',  //取车位置
	carTypeId:'', //车辆类型
	carNum:'', //车牌号
	vehiclePhotos:'',  //整车照片
	repairPhotos:'', //维修照片
	status:'0',  //预约状态
	deleted:'0',
	
})



const vehicleOptions = ref([
  { text: '轿车', value: '0' },
  { text: 'SUV', value: '1' },
  { text: 'MPV', value: '2' },
  { text: '货车', value: '3' }
]) 
const onVehicleTypeChange = (e) => {
  formData.value.carTypeId = e;
}

//  图片上传
function select(e) {
  uploadFile(e.tempFilePaths[0], 'vehiclePhotos');
	// console.log(e.tempFilePaths[0])
}
function select2(e) {
  uploadFile(e.tempFilePaths[0], 'repairPhotos');
	// console.log(e.tempFilePaths[0])
}

const uploadFile = (filePath, type) => {
  uni.showLoading({
    title: '上传中...'
  });
  uni.uploadFile({
    url: baseUrl+'/file/upload', // 替换为你的实际上传接口
    filePath: filePath,
    name: 'file',
    header: {
					Authorization: uni.getStorageSync('Token')
				},
    formData: {
      'type': type
    },
    success: (res) => {
      const data = JSON.parse(res.data);
      // console.log(data);
      if(data.code === 200) {
        if(type === 'vehiclePhotos') {
          formData.value.vehiclePhotos = data.data.url;
          console.log("整张照片"+formData.value.vehiclePhotos);
        }if(type === 'qrcode'){
          formData.value.verificationImg = data.data.url;
          console.log("核销码"+formData.value.verificationImg);
        }
         else {
          if(formData.value.repairPhotos) {
            formData.value.repairPhotos += ',' + data.data.url; // 已有照片则追加
          } else {
            formData.value.repairPhotos = data.data.url; // 第一张照片
          }     
        }
        uni.showToast({
          title: '上传成功',
          icon: 'success'
        });
      }
    },
    fail: (err) => {
      console.error(err);
      uni.showToast({
        title: '上传失败',
        icon: 'none'
      });
    },
    complete: () => {
      uni.hideLoading();
    }
  });
}

// const submitForm1=()=>{
// // 跳转到成功页面 没有历史记录
// formData.value.verificationCode='55LUJ6HP'
//   uni.redirectTo({
//     url: `/pages/index/cheliangweixiu/yuyuechenggong?verificationCode=${formData.value.verificationCode}`
//   });
// }
// 提交表单
const submitForm = () => {
	// 生成8位随机核销码
	formData.value.verificationCode = Math.random().toString(36).slice(2, 10).toUpperCase();
	// 设置提交时间为当前时间
	formData.value.submitTime = formatDateTime();
  // 表单验证
  if (!formData.value.name) {
    uni.showToast({
      title: '请输入车主姓名',
      icon: 'none'
    });
    return;
  }
  if (!formData.value.phone) {
    uni.showToast({
      title: '请输入联系方式',
      icon: 'none'
    });
    return;
  }
  if (!formData.value.reservationTime) {
    uni.showToast({
      title: '请选择预约时间',
      icon: 'none'
    });
    return;
  }
  if (formData.value.type === '1' && !formData.value.location) {
    uni.showToast({
      title: '请输入取车位置',
      icon: 'none'
    });
    return;
  }
  if (!formData.value.carTypeId) {
    uni.showToast({
      title: '请选择车辆类型',
      icon: 'none'
    });
    return;
  }
  if (!formData.value.carNum) {
    uni.showToast({
      title: '请输入车牌号',
      icon: 'none'
    });
    return;
  }
  if (!formData.value.vehiclePhotos) {
    uni.showToast({
      title: '请上传整车照片',
      icon: 'none'
    });
    return;
  }
  if (!formData.value.repairPhotos) {
    uni.showToast({
      title: '请上传维修部位照片',
      icon: 'none'
    });
    return;
  }

  uni.showLoading({
    title: '提交中...'
  });
  uni.request({
    url: baseUrl+'/yyq/reservation',
    method: 'POST',
    data: formData.value,
    header: {
		Authorization: uni.getStorageSync('Token')
	},
      success: (res) => {
        uni.hideLoading();
        if(res.data && res.data.code === 200) { // 检查后端返回的状态码
          // console.log('表单提交成功：', res.data);
          uni.showToast({
            title: '提交成功',
            icon:'success'
          });
         uni.redirectTo({
           url: `/pages/index/cheliangweixiu/yuyuechenggong?verificationCode=${formData.value.verificationCode}`
         });
		  
        } else {
          uni.showToast({
            title: res.data.message || '提交失败',
            icon: 'none'
          });
        }
      },  
  });
};
</script>

<style scoped>
page {
  background-color: #ffffff;
  height: 100%;
}
.container {
  padding: 10px 30px;
}
.repair-mode {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.repair-mode text{
	margin-right: 50rpx;
	font-weight: 600;
}
.customer-info,
.vehicle-info {
  margin-bottom: 20px;
}
.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  display: block;
}
.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.form-item text {
  width: 100px;
}
input {
  flex: 1;
  height: 36px;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 0 10px;
}
.picker-view {
  flex: 1;
  height: 36px;
  border: 1px solid #ccc;
  border-radius: 4px;
  display: flex;
  align-items: center;
  padding: 0 10px;
}
.submit-button {
	margin-top: 40px;
  width: 100%;
  height: 44px;
  border-radius: 4px;
}
</style>